package cn.chia.back.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import cn.chia.back.dao.IUserDAO;
import cn.chia.pojo.User;

@Component
public class UserDAOImpl extends HibernateDaoSupport implements IUserDAO {

	/**
	 * 自动将hibernateTemplate 通过构造方法注入到DAOImpl中
	 * @param hibernateTemplate
	 */
	@Autowired
	public UserDAOImpl(HibernateTemplate hibernateTemplate){
		super.setHibernateTemplate(hibernateTemplate);
	}
	
	
	public void doCreate(User vo) throws Exception {
		super.getHibernateTemplate().save(vo);
	}

	public void doRemove(Integer id) throws Exception {
		super.getHibernateTemplate().delete(findById(id));
	}

	public void doUpdate(User vo) throws Exception {
		super.getHibernateTemplate().update(vo);
	}

	public List<User> findAll() throws Exception {
		return super.getHibernateTemplate().loadAll(User.class);
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll(int pageNo, int pageSize, String keyword,
			String column) throws Exception {
		DetachedCriteria c = DetachedCriteria.forClass(User.class); //Criteria完成分页查询。 
		c.add(Restrictions.like(column, "%" + keyword + "%"));
		List all = super.getHibernateTemplate().findByCriteria(c, (pageNo-1)*pageSize,pageSize);
		
		return all;
	}

	public User findById(Integer id) throws Exception {
		return super.getHibernateTemplate().get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	public int getAllCount(String keyword, String column) throws Exception {
		String hql = "SELECT COUNT(u) FROM User AS u WHERE u."+column+" LIKE ?";
		List all = super.getHibernateTemplate().find(hql, "%" + keyword +"%");
		return ((Long)all.get(0)).intValue();
	}


	public User findById(int userid) throws Exception {
		
		return super.getHibernateTemplate().load(User.class, userid);
	}



	public User findByWid(String wid) throws Exception {
		String hql = "FROM User AS u WHERE u.wid =?";
		Query query = getSession().createQuery(hql);
		List list = query.setString(0, wid).list();
		if (list.size() == 0) {
			return null;
		}else{
		return (User) query.list().get(0);
		}
		
	}
	
	
	
	
	@SuppressWarnings("unchecked")
	public User login(User user) throws Exception {
		String hql = "FROM User AS u WHERE u.tname=? AND u.mob=?";
		List<User> allUser = super.getHibernateTemplate().find(hql, user.getTname(), user.getMob());
		User loginUser = new User();
		if(allUser != null && allUser.size()>0){
			loginUser = allUser.get(0);
			user.setWid(loginUser.getWid());
			user.setUserid(loginUser.getUserid());
			user.setFlag(loginUser.getFlag());
			//user.setAddresses(loginUser.getAddresses());
		}
		return loginUser;
	}



}
